/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mytdev.commons.action;

import java.beans.ExceptionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.mytdev.commons.action.Action.Result.FAILURE;
import static com.mytdev.commons.action.Action.State.DONE;
import static com.mytdev.commons.action.Action.State.PENDING;
import static com.mytdev.commons.action.Action.State.STARTED;

/**
 * An abstract Action that handles the action life cycle. Sub classes should 
 * just override the perform() method.
 * 
 * @author Yann D'Isanto
 */
public abstract class AbstractAction implements Action {

    private State state = PENDING;
    private Result result = null;
    private final List<ExceptionListener> listeners = Collections.synchronizedList(new ArrayList<ExceptionListener>());

    @Override
    public void addExceptionListener(ExceptionListener listener) {
        synchronized(listeners) {
            listeners.add(listener);
        }
    }

    @Override
    public Result getResult() {
        return result;
    }

    @Override
    public State getState() {
        return state;
    }
    
    @Override
    public void removeExceptionListener(ExceptionListener listener) {
        synchronized(listeners) {
            listeners.remove(listener);
        }
    }

    @Override
    public void run() {
        synchronized(this) {
            if(PENDING.equals(state)) {
                state = STARTED;
            } else {
                return;
            }
        }
        try {
            result = perform();
        } catch (Exception ex) {
            result = FAILURE;
            fireExceptionThrown(ex);
        } finally {
            state = DONE;
        }
    }

    /**
     * Reports a thrown exception.
     * @param ex the exception.
     */
    protected void fireExceptionThrown(Exception ex) {
        synchronized(listeners) {
            for (ExceptionListener listener : listeners) {
                listener.exceptionThrown(ex);
            }
        }
    }
    
    /**
     * Performs the action and returns its result.
     * @return the execution result.
     * @throws Exception If an error occurs during the action execution.
     */
    protected abstract Result perform() throws Exception;
}
